<?php

namespace app\api\dao;

use app\api\model\AliMerchant;
use app\common\model\basic\SubMch;
use Exception;
use think\facade\Db;
use function app\api\dao\pay\RequestServer;

class AliZftDao
{
    public $mch_id;

    private $bank_short = [
        '工商银行' => 'ICBC',
        '交通银行' => 'COMM',
        '招商银行' => 'CMB',
        '民生银行' => 'CMBC',
        '中信银行' => 'CITIC',
        '浦发银行' => 'SPDB',
        '兴业银行' => 'CIB',
        '光大银行' => 'CEB',
        '广发银行' => 'GDB',
        '平安银行' => 'SPABANK',
        '北京银行' => 'BJBANK',
        '华夏银行' => 'HXBANK',
        '农业银行' => 'ABC',
        '建设银行' => 'CCB',
        '邮政储蓄银行' => 'PSBC',
        '中国银行' => 'BOC',
        '宁波银行' => 'NBBANK'
    ];

    public function __construct($mch_id)
    {
        $this->mch_id = $mch_id;
    }

    public function getPagesLists($where, $page, $page_size, $field = '*')
    {
        $AliMerchantModel = new AliMerchant();
        $models = $AliMerchantModel->where($where);
        $data = $models->page($page, $page_size)->field($field)->order('is_pay_account','desc')->order('id','desc')->select();
        foreach ($data as $key => $value) {
            $data[$key]['create_time'] = date('Y-m-d H:i', intval($value['create_time']));
        }
        $counts = $models->count();
        return [
            'page' => $page,
            'page_size' => $page_size,
            'total_count' => $counts,
            'total_page' => ceil($counts / $page_size),
            'data' => $data
        ];
    }

    /***
     * 支付宝进件
     * @param $param
     * @param $zft_config
     * @return mixed
     * @throws Exception
     */
    public function simpleCreate($param, $zft_config)
    {
        $model = new AliMerchant();
        $zft_external_id = $this->mch_id . date('YmdHis') . rand(1000, 9999);
        $data = [
            'binding_alipay_logon_id' => $param['zft_ali_account'],
            'external_id' => $zft_external_id,
            'alias_name'    => $param['sub_mch_name'],
            'sub_scene'     => $param['sub_mch_name'],
            'service_phone' => $param['mobile'],
            'contact_infos' => [
                [
                    'name' => $param['name'],
                    'mobile' => $param['mobile']
                ]
            ],
            'mcc' => '7372',
            'alipay_logon_id' => $param['zft_ali_account'],
            'service' => ['小程序支付']
        ];
        // 结算到 支付宝
        $data['default_settle_rule']['default_settle_type'] = 'alipayAccount';
        $data['default_settle_rule']['default_settle_target'] = $param['zft_ali_account']; // 结算给商户支付宝
        // 结算到银行卡
        if ($param['zft_is_biz_cards']) {
            $data['default_settle_rule']['default_settle_type'] = 'bankCard';
            $data['default_settle_rule']['default_settle_target'] = $param['zft_account_no'];
            $data['biz_cards']['account_holder_name'] = $param['zft_account_name'];
            $data['biz_cards']['account_no'] = $param['zft_account_no'];
            $data['biz_cards']['account_inst_province'] = $param['zft_account_province'];
            $data['biz_cards']['account_inst_city'] = $param['zft_account_city'];
            $data['biz_cards']['account_branch_name'] = $param['zft_account_branch_name'];
            $data['biz_cards']['usage_type'] = $param['zft_usage_type'];
            $data['biz_cards']['account_type'] = 'DC'; // DC 为借记卡
            $data['biz_cards']['account_inst_name'] = $param['zft_account_inst_name'];
            if (isset($this->bank_short[$param['zft_account_inst_name']]) && $this->bank_short[$param['zft_account_inst_name']]) {
                $data['biz_cards']['account_inst_id'] = $this->bank_short[$param['zft_account_inst_name']];
            } else {
                throw new Exception('银行不存在或为其他银行');
            }
        }
        $save_data = [
            'mch_id' => $this->mch_id,
            'sub_mch_id' => $param['sub_mch_id'],
            'sub_mch_name' => $param['sub_mch_name'],
            'name' => $param['name'],
            'mobile' => $param['mobile'],
            'zft_ali_name' => $param['zft_ali_name'],
            'zft_ali_account' => $param['zft_ali_account'],
            'zft_is_biz_cards' => $param['zft_is_biz_cards'] ?? '',
            'zft_account_name' => $param['zft_account_name'] ?? '',
            'zft_account_no' => $param['zft_account_no'] ?? '',
            'zft_account_province' => $param['zft_account_province'] ?? '',
            'zft_account_city' => $param['zft_account_city'] ?? '',
            'zft_account_branch_name' => $param['zft_account_branch_name'] ?? '',
            'zft_usage_type' => $param['zft_usage_type'] ?? '',
            'zft_account_inst_name' => $param['zft_account_inst_name'] ?? '',
            'zft_external_id' => $zft_external_id,
            'zft_config' => $zft_config,
            'status' => 1,
            'create_time' => time(),
            'update_time' => time()
        ];
        Db::startTrans();
        try {
            $request_data = json_encode($data);
            $request_body = RequestServer($this->mch_id, 'ali/Zft/simpleCreate', ['zft_config' => $zft_config, 'json' => $request_data]);
            $save_data['zft_order_id'] = $request_body['order_id'] ?? '123';
            if ($param['id']){
                $model->update($save_data, ['id' => $param['id']]);
            }else{
                $model->insertGetId($save_data);
            }
            Db::commit();
            return $request_body;
        } catch (Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

    public function copy($id, $sub_mch_id,$sub_mch_name)
    {
        $model    = new AliMerchant();
        $merchant = $model->where('id', '=', $id)->find();
        if (!$merchant) {
            throw new Exception('商户不存在');
        }
        if ($merchant['sub_mch_id'] == $sub_mch_id){
            throw new Exception('该商户下已存在，不允许复制');
        }
        $save_data = [
            'mch_id' => $this->mch_id,
            'sub_mch_id' => $sub_mch_id,
            'sub_mch_name' => $sub_mch_name,
            'name' => $merchant['name'],
            'mobile' => $merchant['mobile'],
            'zft_ali_name' => $merchant['zft_ali_name'],
            'zft_ali_account' => $merchant['zft_ali_account'],
            'zft_is_biz_cards' => $merchant['zft_is_biz_cards'] ?? '',
            'zft_account_name' => $merchant['zft_account_name'] ?? '',
            'zft_account_no' => $merchant['zft_account_no'] ?? '',
            'zft_account_province' => $merchant['zft_account_province'] ?? '',
            'zft_account_city' => $merchant['zft_account_city'] ?? '',
            'zft_account_branch_name' => $merchant['zft_account_branch_name'] ?? '',
            'zft_usage_type' => $merchant['zft_usage_type'] ?? '',
            'zft_account_inst_name' => $merchant['zft_account_inst_name'] ?? '',
            'zft_external_id' => $merchant['zft_external_id'] ?? '',
            'zft_order_id' => $merchant['zft_order_id'] ?? '',
            'smid' => $merchant['smid'] ?? '',
            'status' => $merchant['status'],
            'zft_config' => $merchant['zft_config'],
            'copy_id' => $id,
            'create_time' => time(),
            'update_time' => time()
        ];
        $id = $model->insertGetId($save_data);
        if ($id){
            return $merchant['zft_ali_account'];
        }
        throw new Exception('复制失败，请重试～');
    }

    public function setPayAccount($id,$is_pay_account,$sub_mch_id)
    {
        $model = new AliMerchant();
        $subMchModel = new SubMch();
        $merchant = $model->where('id', '=', $id)->find();
        if (!$merchant) {
            throw new Exception('商户不存在');
        }
        if ($is_pay_account) {
            $is_exists = $model->where('sub_mch_id','=',$sub_mch_id)->where('is_pay_account','=',1)->count();
            if ($is_exists){
                throw new Exception('该商户已存在收款账户，不允许重复设置, 如需设置收款账户，请先关闭其他收款账户');
            }
        }
        $subMch = $subMchModel->where('id', '=', $sub_mch_id)->find();
        if (empty($subMch)){
            throw new Exception('商户不存在');
        }
        Db::startTrans();
        try {
            if ($is_pay_account){
                $subMch->ali_pay_sub_mch_id = $merchant['smid'];
                $subMch->update_time = time();
                $subMch->save();
            }else{
                $subMch->ali_pay_sub_mch_id = '';
                $subMch->update_time = time();
                $subMch->save();
            }
            $merchant->is_pay_account  = $is_pay_account;
            $merchant->update_time     = time();
            $merchant->save();
            Db::commit();
            return $merchant;
        }catch (\Exception $exception){
            Db::rollback();
            throw new Exception($exception->getMessage());
        }

    }

    public function getDetails($id,$sub_mch_name)
    {
        if (empty($id)){
            return $this->dafaultData($sub_mch_name);
        }
        $AliMerchantModel = new AliMerchant();
        $models = $AliMerchantModel->where('id','=',$id)->find();
        if (empty($models)){
            return $this->dafaultData($sub_mch_name);
        }
        return  $models;
    }

    public function dafaultData($sub_mch_name)
    {
        return [
            'id' => 0,
            'sub_mch_name' => $sub_mch_name,
            'zft_ali_account' => '',
            'zft_ali_name' => '',
            'mobile' => '',
            'name' => '',
            'zft_is_biz_cards' => '',
            'zft_account_name' => '',
            'zft_account_no' => '',
            'zft_account_province' => '',
            'zft_account_city' => '',
            'zft_account_branch_name' => '',
            'zft_usage_type' => '',
            'zft_account_inst_name' => '',
            'smid' => '',
            'status' => '',
            'copy_id' => '',
            'create_time' => '',
            'update_time' => '',
        ];
    }
}